package ch6;

import java.util.HashMap;
import java.util.Map;

/**
 * 无状态对象错误示例：
 * 多个线程访问本身不包含状态的对象也可能存在共享状态示例
 * 一个类即使不包含任何实例变量或者静态变量，执行这个类方法的多个线程仍然可能存在共享状态
 * doSomething()方法的多个执行线程是在共享同一个UnsafeSingleton实例，则UnsafeSingleton类的实例变量
 * state1，就成为这些线程的共享状态。
 */

public class BrokenStatelessObject {
    public String doSomething(String s) {
        UnsafeSingleton us = UnsafeSingleton.INSTANCE;
        int i = us.doSomething(s);
        UnsafeStateFullObject sfo = new UnsafeStateFullObject();
        String str = sfo.doSomething(s, i);
        return str;
    }

    public String doSomething1(String s) {
        UnsafeSingleton us = UnsafeSingleton.INSTANCE;
        UnsafeStateFullObject sfo = new UnsafeStateFullObject();
        String str;
        synchronized (this) {
            str = sfo.doSomething(s, us.doSomething(s));
        }
        return str;
    }


    enum UnsafeSingleton {
        INSTANCE;

        public int state1;

        public int doSomething(String s) {
            // 省略其他代码
            return 0;
        }
    }
}